package mail;

import beans.SessionManagedBean;
import groups.ExerciseGroup;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import lecture.Lecture;
import lecture.LectureAdminManagedBean;
import lecture.LectureManagedBean;
import user.User;
import user.UserAdminManagedBean;

/**
 *
 * @author Thorsten Ludwig
 */

@ManagedBean(name="sendMailBean")
@RequestScoped
public class SendMailManagedBean {
    @Resource(name = "mail/cismail")
    private Session mailSession;

    private boolean set;
    
    private List<ExerciseGroup> choosenGroups;
    
    private String subject;
    
    private String messageText;
    
    private String modus;
    
    public void send() {
        FacesContext context = FacesContext.getCurrentInstance();
        LectureManagedBean lb = context.getApplication().evaluateExpressionGet(context, "#{lectureBean}", LectureManagedBean.class);
        Lecture lecture = lb.getLecture();
        
        if (modus.equalsIgnoreCase("Alle Studenten")) {
            
            this.sendMessage(subject, messageText, lecture.getStudents());
        } else if (modus.equalsIgnoreCase("Alle Tutoren")) {
            this.sendMessage(subject, messageText, lecture.getTutors());
        } else if (modus.equalsIgnoreCase("Allen")) {
            this.sendMessage(subject, messageText, lecture.getInfo().getUsers());
        } else if (modus.equalsIgnoreCase("Eigenen Studenten")) {
            List<User> user = new ArrayList<User>();
            UserAdminManagedBean ua = context.getApplication().evaluateExpressionGet(context, "#{userAdminBean}", UserAdminManagedBean.class);        
            for (ExerciseGroup eg: this.choosenGroups) {
                for (String s: eg.getStudents()) {
                    user.add(ua.getUser(s));
                }
            }
            
            this.sendMessage(subject, messageText, user);
        } else {
            System.out.println("Keine Option ausgewählt");
        }
        
    }
    
    public List<ExerciseGroup> getGroups() {
        FacesContext context = FacesContext.getCurrentInstance();        
        SessionManagedBean sb = (SessionManagedBean) context.getApplication().evaluateExpressionGet(context, "#{sessionBean}", SessionManagedBean.class);
        LectureAdminManagedBean lectureAdmin = context.getApplication().evaluateExpressionGet(context, "#{lectureAdminBean}", LectureAdminManagedBean.class);
        User user = sb.getUser();
        Lecture lecture = sb.getLectureBean().getLecture();
        List<ExerciseGroup> list = new ArrayList<ExerciseGroup>();
        for (ExerciseGroup eg: lectureAdmin.getUserExerciseGroupsWhereLeader(user)) {
            if (eg.getLecture().getInfo().getName().equals(lecture.getInfo().getName()))
                list.add(eg);
                    
        }
        if (list.size() == 1) {
            this.set = true;
            this.choosenGroups = list;
        }
        return list;
    }
    
      public void sendMessage(String subject, String messageText ,List<User> user ) {
        FacesContext context = FacesContext.getCurrentInstance();        
        SessionManagedBean sb = (SessionManagedBean) context.getApplication().evaluateExpressionGet(context, "#{sessionBean}", SessionManagedBean.class);
        User currentUser = sb.getUser();
        Lecture lecture = sb.getLectureBean().getLecture();
          
        Message msg = new MimeMessage(mailSession);
        try {
          
          for (User u: user) {
              System.out.append(u.getUsername());
              msg.setRecipient(RecipientType.BCC, 
                      new InternetAddress(u.getEmail(), u.getFirstName() + " " + u.getLastName()));
          }
            
          msg.setFrom(new InternetAddress(currentUser.getEmail(), currentUser.getFirstName() + " " + currentUser.getLastName()));
          msg.setSubject(subject);          
          msg.setText(messageText);
          Transport.send(msg);
          lecture.addMail(new Mail(currentUser,modus,subject,messageText));
          System.out.println("E-Mail gesendet");
        }
        catch(MessagingException me) {
          // manage exception
            me.printStackTrace();
        }
        catch(UnsupportedEncodingException uee) {
          // manage exception
            uee.printStackTrace();
        }
      }

    public String getMessageText() {
        return messageText;
    }

    public void setMessageText(String messageText) {
        this.messageText = messageText;
    }

    public String getModus() {
        return modus;
    }

    public void setModus(String modus) {
        this.modus = modus;
    }

    public boolean isSet() {
        return set;
    }

    public void setSet(boolean set) {
        this.set = set;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public List<ExerciseGroup> getChoosenGroups() {
        return choosenGroups;
    }

    public void setChoosenGroups(List<ExerciseGroup> choosenGroups) {
        this.choosenGroups = choosenGroups;
    }
      
    public List<String> getItems() {
        List<String> items = new ArrayList<String>();
        items.add("Alle Studenten");
        items.add("Alle Tutoren");
        items.add("Eigenen Studenten");
        items.add("Allen");
        return items;
    }  
    

}
